package cn.zhentao.filter;

import cn.zhentao.util.JwtUtils;
import cn.zhentao.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired(required = false)
    private UserServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestPath = request.getRequestURI();
        
        // 跳过登录和注册相关的路径
        if (requestPath.equals("/login") || requestPath.startsWith("/login/") ||
            requestPath.equals("/register") || requestPath.startsWith("/register/") ||
            requestPath.startsWith("/public/") || requestPath.startsWith("/actuator/") ||
            requestPath.startsWith("/h2-console/") || requestPath.equals("/error") ||
            requestPath.startsWith("/XinAi/")) {  // 跳过AI接口路径
            filterChain.doFilter(request, response);
            return;
        }

        String authHeader = request.getHeader("Authorization");
        String token = null;
        String username = null;

        // 启用JWT验证
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
            
            try {
                // 验证JWT令牌
                if (jwtUtils.validateToken(token)) {
                    username = jwtUtils.getUsernameFromToken(token);
                    // 将用户名设置到请求属性中，供后续使用
                    request.setAttribute("username", username);
                    filterChain.doFilter(request, response);
                    return;
                } else {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("{\"code\":401,\"message\":\"无效的登录令牌\"}");
                    return;
                }
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"code\":401,\"message\":\"令牌验证失败\"}");
                return;
            }
        } else {
            // 没有提供Authorization头
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"缺少认证令牌\"}");
            return;
        }
    }
} 